import numpy as np
import pandas as pd


# 均方差决策法确定指标权重
def get_weight_by_msd(proportion_df):
    rows = proportion_df.shape[0]
    # ------老方法------
    sgms = []
    for column in proportion_df.columns:
        # 计算均值
        ej = sum(proportion_df[column]) / rows
        err_sum = 0
        for x_tj in proportion_df[column]:
            err_sum += (x_tj - ej) * (x_tj - ej)
        sgm = np.sqrt(err_sum / rows)
        sgms.append(sgm)
    print('---------指标均方差-老方法----------')
    print(sgms)
    # ------老方法------
    mses = np.sqrt(1 / rows * np.array([sum([(x_tj - sum(proportion_df[column]) / rows) * (
            x_tj - sum(proportion_df[column]) / rows) for x_tj in proportion_df[column]]) for column in
                                        proportion_df.columns]))
    mses_df = pd.Series(mses, index=proportion_df.columns, name='指标均方差')
    print('---------指标均方差-numpy方法----------')
    print(mses_df)

    # 计算指标权重
    weights = mses_df / sum(mses_df)
    weights.name = '均方差确定指标权重'

    print('-----------均方差确定指标权重-----------')
    print(weights)

    return weights
